﻿Imports System.IO
Imports Microsoft.SqlServer.Management.Smo
Imports Microsoft.SqlServer.Management.Common
Imports System.Text.RegularExpressions
Imports BUS


Public Class frmSaoLuuDuLieu
    Private pathFolder As String = "D:\\Backup"
    Private fileBackupName As String
    Private dbName As String = "qlBanHangVBNet1"
    Private severName As String = ".\SQLEXPRESS"


    Private Sub txtDuongDan_ButtonClick(sender As Object, e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles txtDuongDan.ButtonClick
        If e.Button.Tag.ToString = "btnOpenFolder" Then
            Dim dlg As New FolderBrowserDialog()
            If DialogResult.OK = (New openFolder(dlg).Invoke()) Then
                txtDuongDan.Text = dlg.SelectedPath
                pathFolder = dlg.SelectedPath
            End If
        End If
    End Sub

    Private Sub btnThucHien_Click(sender As Object, e As EventArgs) Handles btnThucHien.Click
        
        btnDong.Enabled = False
        btnThucHien.Enabled = False
        txtDuongDan.Properties.Buttons(0).Enabled = False
        Me.CloseBox = False

        Dim myServer As New Server(severName)
        Try
            myServer.ConnectionContext.LoginSecure = True
            myServer.ConnectionContext.Connect()
            Dim myDatabase As Database = myServer.Databases(dbName)
            BackupDatabaseFull(myServer, myDatabase)
        Catch ex As Exception
            DevExpress.XtraEditors.XtraMessageBox.Show(ex.InnerException.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error)
            btnDong.Enabled = True
            btnThucHien.Enabled = True
            txtDuongDan.Properties.Buttons(0).Enabled = True
            Me.CloseBox = True
        Finally
            If myServer.ConnectionContext.IsOpen Then
                myServer.ConnectionContext.Disconnect()
            End If
        End Try
        btnDong.Enabled = True
        btnThucHien.Enabled = True
        txtDuongDan.Properties.Buttons(0).Enabled = True
        Me.CloseBox = True
    End Sub

    Dim x As Integer = 0

    Private Sub btnDong_Click(sender As Object, e As EventArgs) Handles btnDong.Click
        Me.Close()
    End Sub

    Private Sub frmKhoiPhuc_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        dbName = HeThongBUS.layDataBase()
        severName = HeThongBUS.layTenSever()
        If Directory.Exists(pathFolder) = False Then
            Directory.CreateDirectory(pathFolder)
        End If

        Dim datenow As String = DateTime.Now.ToShortDateString() + "_" + DateTime.Now.ToShortTimeString()
        Dim name As String = datenow.Replace("/"c, "-"c).Replace(" "c, "_"c).Replace(":"c, "-"c)
        fileBackupName = "QuanLyBanHang_" + name + ".bak"
        txtDuongDan.Text = pathFolder
        txtTenTapTin.Text = fileBackupName

        proTienTrinh.Properties.PercentView = True
        proTienTrinh.Properties.Maximum = 100
        proTienTrinh.Properties.Minimum = 0
    End Sub

    Private Sub BackupDatabaseFull(myServer As Server, myDatabase As Database)
        Dim bkpDBFull As New Backup()
        bkpDBFull.Action = BackupActionType.Database
        bkpDBFull.Database = myDatabase.Name

        Dim device As New BackupDeviceItem(pathFolder.Replace("\", "\\") + "\\" + fileBackupName, DeviceType.File)

        bkpDBFull.Devices.Add(device)
        bkpDBFull.BackupSetName = "QuanLyBanHang"
        bkpDBFull.BackupSetDescription = "QuanLyBanHang database - Full Backup"
        bkpDBFull.ExpirationDate = DateTime.Today.AddDays(10)
        bkpDBFull.Initialize = False
        AddHandler bkpDBFull.PercentComplete, AddressOf CompletionStatusInPercent
        AddHandler bkpDBFull.Complete, AddressOf Backup_Completed
        bkpDBFull.SqlBackup(myServer)
    End Sub

    Private Sub CompletionStatusInPercent(sender As Object, args As PercentCompleteEventArgs)
        If proTienTrinh.Position < proTienTrinh.Properties.Maximum Then
            If (proTienTrinh.Position + args.Percent) <= 100 Then
                proTienTrinh.Position += args.Percent
            Else
                proTienTrinh.Position = 100
                btnDong.Enabled = True
                btnThucHien.Enabled = True
                txtDuongDan.Properties.Buttons(0).Enabled = True
                Me.CloseBox = True
            End If
        End If
    End Sub

    Private Sub Backup_Completed(sender As Object, args As ServerMessageEventArgs)
        DevExpress.XtraEditors.XtraMessageBox.Show("Sao lưu dữ liệu thành công", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information)
        HeThongBUS.themNhatKy(frmMain.maND,"Hệ Thống","Sao Lưu Dữ Liệu","")
    End Sub

    Private Sub txtTenTapTin_Leave(sender As Object, e As EventArgs) Handles txtTenTapTin.Leave
        fileBackupName = txtTenTapTin.Text
        ' ([A-Za-z0-9_-]+).bak
        Dim match As Match = Regex.Match(txtTenTapTin.Text.ToString, "([A-Za-z0-9_-]+).bak", RegexOptions.IgnoreCase)
        If match.Success = False Then
            fileBackupName = fileBackupName + ".bak"
            txtTenTapTin.Text = fileBackupName
        End If
    End Sub
End Class